﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace WS.EKA.Utility
{
    public class XmlSerializerHelper
    {
        public static T Deserialize<T>(string name) where T:class
        {
            string path = GetFilePath(name);
            using (var stream = File.Open(path, FileMode.Open))
            {
                XmlSerializer se = new XmlSerializer(typeof(T));
                return se.Deserialize(stream) as T;
            }
        }

        /// <summary>
        /// if name is null then not save xml file to disk 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string Serialize<T>(T t,string name=null) where T : class
        {
            string path = GetFilePath(name);
            XmlSerializer se = new XmlSerializer(typeof(T));
            using(var stream = new MemoryStream())
            {
                se.Serialize(stream, t);
                if (!string.IsNullOrEmpty(name))
                {
                    using (StreamWriter file = new StreamWriter(path))
                    {
                        se.Serialize(file, t);
                    }
                }
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// First search base directory ,then bin directory
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string GetFilePath(string fileName)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
            if (File.Exists(path))
            {
                return path;
            }
            path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,@"bin\"+fileName);
            if (File.Exists(path))
            {
                return path;
            }
            throw new FileNotFoundException(fileName+"不存在！");
        }
    }
}
